response.headers.add('X-Script-Version', 'runtime-redis-1.0')

function connect() {
    var data = payload.get().body.toObject()
    if (data.name && data.uri) {
        var result = REDIS.new(data.name, data.uri)
        if (result == data.name) {
            return okMsg("连接成功")
        }
        return errMsg(507, "连接失败")
    }
    return errMsg(507, '参数错误')
}

function get() {
    var data = payload.get().body.toObject()
    if (data.name && data.key) {
        var result = REDIS.get(data.name, data.key)
        if (result) {
            return okMsg(result)
        }
        return errMsg(507, "查询失败")
    }
    return errMsg(507, '参数错误')
}

function set() {
    var data = payload.get().body.toObject()
    if (data.name && data.key && data.value) {
        var result = REDIS.set(data.name, data.key, data.value, data.ttl ? data.ttl : -1)
        if (result) {
            return okMsg(result)
        }
        return errMsg(507, "赋值失败")
    }
    return errMsg(507, '参数错误')
}

function del() {
    var data = payload.get().body.toObject()
    if (data.name && data.sql) {
        var result = REDIS.del(data.name, data.key)
        if (result) {
            return okMsg(result)
        }
        return errMsg(507, "查询失败")
    }
    return errMsg(507, '参数错误')
}

function keys() {
    var data = payload.get().body.toObject()
    if (data.name && data.sql) {
        var result = REDIS.keys(data.name, data.pattern)
        if (result) {
            return okMsg(result)
        }
        return errMsg(507, "查询失败")
    }
    return errMsg(507, '参数错误')
}

function flush() {
    var script = payload.get().query['name[]']
    for (var i = 0; i < script.length; i++) {
        REDIS.flush(script[i])
    }
    return okMsg("操作成功")
}

function close() {
    var script = payload.get().query['name[]']
    for (var i = 0; i < script.length; i++) {
        REDIS.close(script[i])
    }
    return okMsg("操作成功")
}

function list() {
    return okMsg(REDIS.list())
}

function main() {
    // 验证用户权限
    'use api/user/acl/excerpt.js'

    switch (payload.get().method) {
        case 'GET':
            return list()
        case 'POST':
            return keys()
        case 'PUT':
            return connect()
        case 'DELETE':
            return close()
        default:
            response.status.notFound()
            return `404 page not found`
    }
}